import {Fab} from "@mui/material";
import Dialog from "@mui/material/Dialog";
import DialogTitle from "@mui/material/DialogTitle";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogActions from "@mui/material/DialogActions";
import Button from "@mui/material/Button";
import {createTheme, ThemeProvider} from "@mui/material/styles";
import React, {useEffect} from "react";
import {getQPlayStatus} from "../../utils/request/qrequest";
import './LoginQQ.css';

const store = window.electron_store;
const ipcRenderer = window.ipcRenderer;
const theme = createTheme({
    palette: {
        primary: {
            main: 'rgba(255,255,255,0)',
            contrastText: 'rgba(255,255,255,0)',
            light: 'rgba(255,255,255,0)'
        },
    },
});

export default function LoginQQ(props){
    const [open, setOpen] = React.useState(false);
    const [text, setText] = React.useState('从QQ音乐官网获取');
    const [isLogin, setIsLogin] = React.useState(false);
    const [user, setUser] = React.useState("");


    const handleClickOpen = () => {
        if(user !== "") {
            setText('现有账号: ' + user+'  点击确认退出登录')
        }
        else
        setText('点击确认，从QQ音乐官网获取登录')
        setOpen(true);

    };
    const saveCookie = (c) =>{

        store.set('qqcookie',c)
    }
    const dealCookie = (strings) => {
        let result = '';
        if(strings === '' || strings === undefined){
            return undefined;
        }
        strings = strings.split(';');
        strings.forEach(element => {
           //console.log(element)
            let is = element.split('=');
            if(is[0].trim() === 'uin'){
                result = is[1].trim()
            }
        });
        return result;
    }
    useEffect(() => {
        ipcRenderer.on('getQQcookies',(event, message) => {
           //console.log(message)
            saveCookie(message);
            setTimeout(() => {
                init();
                setOpen(false)
            }, 2000);
        })
        init();
    },[])
    const handleClose = () => {

        setOpen(false);
    };

    //通过cookie初始化状态
    const init = () =>{
        let id = dealCookie(store.get('qqcookie'));
       //console.log("已登录:" + store.get('qqcookie'))
        if (id) {
            getQPlayStatus(id).then((r) => {
               //console.log(r)
                let userName = r.creator?.nick;
                if (userName !== undefined) {
                    setUser(userName);
                    setIsLogin(true);
                }else {
                    saveCookie('')
                    setUser('');
                    setIsLogin(false);
                }
            }).catch(() => {
                saveCookie('')
                setUser('');
                setIsLogin(false);
            })
        }else {
            saveCookie('')
            setUser('');
            setIsLogin(false);
        }
    }

    const handleOk = () => {
        setText('正在准备去获取Cookies')
        if(user !== ''){
            setText('正在退出···')
            saveCookie('')
            init();
            ipcRenderer.send('cleanQQcookie')
            setTimeout(() => {
                setOpen(false);
            }, 2000);
        }else {
            ipcRenderer.send('loginQQwindow');
        }

    };
    const handleClear = () => {
        setText('正在重置···')
        saveCookie('')
        init();
        ipcRenderer.send('cleanQQcookie')
        setTimeout(() => {
            setOpen(false);
        }, 2000);


    };


    return(
        <>
            <div>
                <Dialog open={open} onClose={handleClose}>
                    <DialogTitle>登录QQ</DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            {text}
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClear}>重置qq状态</Button>
                        <Button onClick={handleClose}>取消</Button>
                        <Button onClick={handleOk}>确认</Button>
                    </DialogActions>
                </Dialog>
            </div>
            <div className="content_q">
                <ThemeProvider theme={theme}>
                    <Fab color="primary" ariant="extended" className='fabqq' onClick={handleClickOpen}>
                        <img  width='64px'  height='64px' src={isLogin?'./icoqq.png' : './unicoqq.png'}/>
                    </Fab>
                </ThemeProvider>
            </div>
        </>
    )

}